<template>
  <div>

    <div class="title-box">
      <div>用户注册</div>
    </div>

    <el-form ref="postForm" :model="postForm" :rules="loginRules">

      <el-form-item prop="realName">
        <el-input
          v-model="postForm.realName"
          style="width: 100%"
          placeholder="请输入真实姓名"
          prefix-icon="el-icon-user"
        />
      </el-form-item>

      <el-form-item prop="userName">
        <el-input
          v-model="postForm.userName"
          style="width: 100%"
          placeholder="请输入手机号"
          prefix-icon="el-icon-mobile"
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="postForm.password"
          show-password
          style="width: 100%"
          placeholder="请输入密码"
          type="password"
          prefix-icon="el-icon-lock"
        />
      </el-form-item>

      <el-form-item prop="ensurePassword">
        <el-input
          v-model="postForm.ensurePassword"
          show-password
          style="width: 100%"
          placeholder="请输入确认密码"
          type="password"
          prefix-icon="el-icon-lock"
        />
      </el-form-item>


      <el-form-item>
        <el-button :loading="loading" type="primary" style="width: 100%" @click.native.prevent="handleReg">注册
        </el-button>
      </el-form-item>

      <div style="display: flex; align-items: center; justify-content: flex-end">
        <el-link type="primary" href="/#/login">已有账号</el-link>
      </div>

    </el-form>


  </div>

</template>

<script>
import {mapGetters} from 'vuex'
import rules from '@/utils/rules'

export default {
  data() {
    return {
      postForm: {
        userName: '', // 手机号
        realName: '', // 真实姓名
        password: '', // 密码
        ensurePassword: '', // 确认密码
      },
      loginRules: {
        ...rules,
        ensurePassword: [
          {required: true, trigger: 'blur', message: '确认密码不能为空！'},
          {
            validator: (rule, value, callback) => {
              if (value !== this.postForm.password) {
                callback(new Error('两次输入的密码不一致！'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ],
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters([
      'siteData'
    ])
  },

  methods: {

    handleReg() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/reg', this.postForm)
            .then(() => {
              this.$router.push({path: this.redirect || '/admin/dashboard'})
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    }

  }
}
</script>

